﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using RiskMan.DataClass.Models.Indikators;
using RiskMan.DataClass.Models.Plaza_II;
using TextBox = System.Windows.Controls.TextBox;

namespace RiskMan.Views.Plaza_II
{
    /// <summary>
    /// Interaction logic for TestIndikators.xaml
    /// </summary>
    public partial class TestIndikators
    {
        public TestIndikators()
        {
            InitializeComponent();
            TxbxPath.Text = Properties.Settings.Default.PathTestFile;
            DtgdTestIndikators.ItemsSource = MainWindow.StaticLevel._dataProvider.TestCalculationIndikatorses;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Filter = Properties.Resources.TestIndikators_Button_Click_txt_files____txt____txt_All_files__________;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                TxbxPath.Text = openFileDialog1.FileName;
                Properties.Settings.Default.PathTestFile = openFileDialog1.FileName;
                Properties.Settings.Default.Save();
            }

        }

        private void TxbxLoad_Click(object sender, RoutedEventArgs e)
        {
           

            try
            {
                string[] strings;
                if (File.Exists(Properties.Settings.Default.PathTestFile))
                    using (StreamReader sr = new StreamReader(Properties.Settings.Default.PathTestFile))
                    {
                        string s = sr.ReadToEnd();
                        string[] divizorz = new string[] { "\r\n" };
                        strings = s.Split(divizorz, StringSplitOptions.None);
                        int row = 1;
                        if (strings.Length > 0)
                        {
                            string[] tmpstring;
                            for (int i = 1; i < strings.Length; i++)
                            {
                                tmpstring = strings[i].Split(',');
                                if (tmpstring.Length > 1)
                                    MainWindow.StaticLevel._dataProvider.TestCalculationIndikatorses.Add
                                        (new TestCalculationIndikators()
                                        {
                                            Date = Convert.ToDateTime(tmpstring[3].Insert(2, ":").Insert(5, ":")),
                                            Last = Convert.ToDouble(tmpstring[4].Replace('.', ',')),
                                            IndexRow = row
                                        });
                                row = row + 1;
                            }

                        }
                    }
            }
            catch
            {


            }


            //Расчет индикатора пивот
            IndikatorPivot pivot = new IndikatorPivot();
            IndikatorMacd macd = new IndikatorMacd();
            double bigHighPivot = 0;
            double bigLowPivot = 0;
            double smallHighPivot = 0;
            double smallLowPivot = 0;
            double priceOPen = 0;

            //исключаем повтороный вход по пивоту, при неудачной сделке
            double lastpricePivotUp = 0;
            double lastpricePivotDown = 0;
            bool boolUseLastpricePivotUp = false;
            bool boolUseLastpricePivotDown = false;

            int countDeal = 0;
            bool signalLong = false;
            bool signalShort = false;
            bool signalLongOpen = false;
            bool signalShortOpen = false;
            var test = MainWindow.StaticLevel._dataProvider.TestCalculationIndikatorses;
            if (MainWindow.StaticLevel._dataProvider.TestCalculationIndikatorses.Count > 0)
            {
                for (int i = 0; i < test.Count; i++)
                {

                    if (i >= 86862)
                    {
                    }

                    #region логика
                    if (i >= Convert.ToInt32(TxbxNumTicksForInit.Text))
                    {
                        test[i].CumProfit = test[i - 1].CumProfit;
                        test[i].CountDeal = countDeal;
                        if (test[i - 1].BigCountDiff >= Convert.ToInt32(TxbxNumTicksForCrossBig.Text) &&
                            test[i - 1].SmallCountDiff >= Convert.ToInt32(TxbxNumTicksForCrossSmall.Text) && !signalLong && !signalShortOpen && !signalLongOpen && !signalShort)
                        {
                            test[i].Comment = "Сигнал на открытие позиции лонг. Цена пивота для открытия=" +
                                              bigLowPivot.ToString();
                            signalLong = true;
                            signalShort = false;
                            signalLongOpen = false;
                            signalShortOpen = false;

                        }

                        if (lastpricePivotDown != bigHighPivot)
                            boolUseLastpricePivotDown = false;
                        if (lastpricePivotUp != bigLowPivot)
                            boolUseLastpricePivotUp = false;

                        if (bigHighPivot != 0 && bigLowPivot != 0)
                        {
                            if (signalShort &&
                                test[i - 1].Last <= bigHighPivot - Convert.ToInt32(TxbxOtstupForBigPivot.Text) &&
                                test[i].Last > bigHighPivot - Convert.ToInt32(TxbxOtstupForBigPivot.Text) &&
                                !signalShortOpen && !signalLongOpen && (lastpricePivotDown != bigHighPivot) && !boolUseLastpricePivotDown)
                            {
                                test[i].Comment = "Открыли позицю шорт. Открытие=" +
                                                  (bigHighPivot - Convert.ToInt32(TxbxOtstupForBigPivot.Text)).ToString()
                                                  + " Пивот=" + bigHighPivot;
                                signalLongOpen = false;
                                signalShortOpen = true;
                                priceOPen = bigHighPivot - Convert.ToInt32(TxbxOtstupForBigPivot.Text);
                                countDeal = countDeal + 1;
                                test[i].CountDeal = countDeal;

                                boolUseLastpricePivotDown = false;

                            }
                        }
                        if (bigHighPivot != 0 && bigLowPivot != 0)
                        {
                            if (signalLong && test[i - 1].Last >= bigLowPivot + Convert.ToInt32(TxbxOtstupForBigPivot.Text) && test[i].Last < bigLowPivot + Convert.ToInt32(TxbxOtstupForBigPivot.Text) &&
                                !signalLongOpen && !signalShortOpen && (!boolUseLastpricePivotUp && lastpricePivotUp != bigLowPivot))
                            {
                                test[i].Comment = "Открыли позицю лонг. Открытие=" +
                                                  (bigLowPivot + Convert.ToInt32(TxbxOtstupForBigPivot.Text)).ToString()
                                                  + " Пивот=" + bigLowPivot.ToString();
                                signalLongOpen = true;
                                signalShortOpen = false;
                                priceOPen = bigLowPivot + Convert.ToInt32(TxbxOtstupForBigPivot.Text);
                                countDeal = countDeal + 1;
                                test[i].CountDeal = countDeal;

                            }

                            if (ChbxRevers.IsChecked == false)
                            {
                                if (test[i - 1].Last <= bigHighPivot - Convert.ToInt32(TxbxProfitForBigPivot.Text) &&
                                    test[i].Last > bigHighPivot - Convert.ToInt32(TxbxProfitForBigPivot.Text) &&
                                    signalLongOpen && priceOPen < bigHighPivot)
                                {
                                    test[i].Comment = "Переворот, закрытие лонг и открытие шорт. Открытие=" +
                                                      (bigHighPivot - Convert.ToInt32(TxbxOtstupForBigPivot.Text))
                                                          .ToString()
                                                      + " Пивот=" + bigHighPivot.ToString();
                                    signalLongOpen = false;
                                    signalShortOpen = true;
                                    test[i].Profit = bigHighPivot - Convert.ToInt32(TxbxProfitForBigPivot.Text) - priceOPen;
                                    test[i].CumProfit = test[i - 1].CumProfit + test[i].Profit;
                                    priceOPen = bigHighPivot;
                                    countDeal = countDeal + 1;
                                    test[i].CountDeal = countDeal;

                                }
                            }
                            else
                            {
                                if (test[i - 1].Last <= bigHighPivot - Convert.ToInt32(TxbxProfitForBigPivot.Text) &&
                                    test[i].Last > bigHighPivot - Convert.ToInt32(TxbxProfitForBigPivot.Text) &&
                                    signalLongOpen && priceOPen < bigHighPivot)
                                {
                                    test[i].Comment = "Закрытие лонг. " +
                                                      (bigHighPivot - Convert.ToInt32(TxbxProfitForBigPivot.Text))
                                                          .ToString()
                                                      + " Пивот=" + bigHighPivot.ToString();
                                    signalLongOpen = false;
                                    signalShortOpen = false;
                                    signalLong = false;
                                    test[i].Profit = bigHighPivot - Convert.ToInt32(TxbxProfitForBigPivot.Text) - priceOPen;
                                    test[i].CumProfit = test[i - 1].CumProfit + test[i].Profit;
                                    priceOPen = bigHighPivot;
                                    boolUseLastpricePivotUp = true;

                                }                                
                            }
                        }
                        #region Закрытие позции
                        if (smallHighPivot != 0 && smallLowPivot != 0 && priceOPen > smallHighPivot)

                            if (test[i - 1].Last <= smallHighPivot - Convert.ToInt32(TxbxOtstupForSmallPivot.Text) && test[i].Last > smallHighPivot - Convert.ToInt32(TxbxOtstupForSmallPivot.Text) && signalLongOpen)
                            {
                                test[i].Comment = "Закрытие лонг малому пивоту. Открытие=" + (smallHighPivot + Convert.ToInt32(TxbxOtstupForSmallPivot.Text)).ToString()
                                                     + " Пивот=" + smallHighPivot.ToString();
                                signalLongOpen = false;
                                signalShortOpen = false;
                                signalLong = false;
                                test[i].Profit = smallHighPivot - Convert.ToInt32(TxbxOtstupForSmallPivot.Text) - priceOPen;
                                test[i].CumProfit = test[i - 1].CumProfit + test[i].Profit;
                                lastpricePivotUp = bigLowPivot;
                                boolUseLastpricePivotUp = true;
                            }
                        #endregion


                        if (test[i - 1].BigCountDiff <= -Convert.ToInt32(TxbxNumTicksForCrossBig.Text) &&
                            test[i - 1].SmallCountDiff < -Convert.ToInt32(TxbxNumTicksForCrossSmall.Text) && !signalLong && !signalShortOpen && !signalLongOpen && !signalShort)
                        {
                            test[i].Comment = "Сигнал на открытие позиции шорт. Цена пивота для открытия=" +
                                              bigHighPivot.ToString();

                            signalLong = false;
                            signalShort = true;
                            signalLongOpen = false;
                            signalShortOpen = false;
                        }
                        if (bigHighPivot != 0 && bigLowPivot != 0)
                        {
                            //if (signalShort && test[i-1].Last <= bigHighPivot - Convert.ToInt32(TxbxOtstupForBigPivot.Text) &&
                            //    test[i].Last >= bigHighPivot - Convert.ToInt32(TxbxOtstupForBigPivot.Text) &&
                            //    !signalShortOpen && !signalLongOpen)
                            //{
                            //    test[i].Comment = "Открыли позицю шорт. Открытие=" +
                            //                      (bigHighPivot - Convert.ToInt32(TxbxOtstupForBigPivot.Text)).ToString()
                            //                      + " Пивот=" + bigHighPivot;
                            //    signalLongOpen = false;
                            //    signalShortOpen = true;
                            //    priceOPen = bigHighPivot;
                            //    countDeal = countDeal + 1;
                            //    test[i].CountDeal = countDeal;

                            //}


                            if (ChbxRevers.IsChecked == false)
                            {
                                if (test[i - 1].Last >= bigLowPivot + Convert.ToInt32(TxbxProfitForBigPivot.Text) &&
                                    test[i].Last < bigLowPivot + Convert.ToInt32(TxbxProfitForBigPivot.Text) &&
                                    signalShortOpen && priceOPen > bigLowPivot)
                                {
                                    test[i].Comment = "Переворот, закрытие шорт и открытие лонг. Открытие=" +
                                                      (bigLowPivot + Convert.ToInt32(TxbxOtstupForBigPivot.Text))
                                                          .ToString()
                                                      + " Пивот=" + bigLowPivot.ToString();
                                    signalLongOpen = true;
                                    signalShortOpen = false;
                                    test[i].Profit = priceOPen - bigLowPivot - Convert.ToInt32(TxbxProfitForBigPivot.Text);
                                    test[i].CumProfit = test[i - 1].CumProfit + test[i].Profit;
                                    priceOPen = bigLowPivot;
                                    countDeal = countDeal + 1;
                                    test[i].CountDeal = countDeal;
                                }
                            }
                            else
                            {
                                if (test[i - 1].Last >= bigLowPivot + Convert.ToInt32(TxbxProfitForBigPivot.Text) &&
                                  test[i].Last < bigLowPivot + Convert.ToInt32(TxbxProfitForBigPivot.Text) &&
                                  signalShortOpen && priceOPen > bigLowPivot)
                                {
                                    test[i].Comment = "Закрытие шорт. " +
                                                      (bigLowPivot + Convert.ToInt32(TxbxProfitForBigPivot.Text))
                                                          .ToString()
                                                      + " Пивот=" + bigLowPivot.ToString();
                                    signalLongOpen = false;
                                    signalShortOpen = false;
                                    signalLong = false;
                                    test[i].Profit = priceOPen - bigLowPivot - Convert.ToInt32(TxbxProfitForBigPivot.Text);
                                    test[i].CumProfit = test[i - 1].CumProfit + test[i].Profit;
                                    priceOPen = bigLowPivot;
                                    boolUseLastpricePivotDown = true;
                                }                              
                            }
                        }
                        #region Закрытие позции
                        if (smallHighPivot != 0 && smallLowPivot != 0 && priceOPen < smallLowPivot)
                            if (test[i - 1].Last >= smallLowPivot + Convert.ToInt32(TxbxOtstupForSmallPivot.Text) && test[i].Last < smallLowPivot + Convert.ToInt32(TxbxOtstupForSmallPivot.Text) && signalShortOpen)
                            {
                                test[i].Comment = "Закрытие шорт малому пивоту. Открытие=" + (smallLowPivot + Convert.ToInt32(TxbxOtstupForSmallPivot.Text)).ToString()
                                                    + " Пивот=" + smallLowPivot.ToString();
                                signalLongOpen = false;
                                signalShortOpen = false;
                                signalLong = false;
                                test[i].Profit = priceOPen - smallLowPivot - Convert.ToInt32(TxbxOtstupForSmallPivot.Text);
                                test[i].CumProfit = test[i - 1].CumProfit + test[i].Profit;
                                lastpricePivotDown = bigHighPivot;
                                boolUseLastpricePivotDown = true;
                            }
                        #endregion




                    }
                    #endregion


                    #region Pivot small

                    if (i - Convert.ToInt32(TxbxSmallPivotHigh.Text) > 0)
                    {
                        if (pivot.Calculation(test, i - Convert.ToInt32(TxbxSmallPivotHigh.Text), Convert.ToInt32(TxbxNumTicksForInit.Text),
                            Convert.ToInt32(TxbxSmallPivotHigh.Text), Convert.ToInt32(TxbxSmallPivotHigh.Text), "HIGH"))
                        {
                            test[i - Convert.ToInt32(TxbxSmallPivotHigh.Text)].SmallPivotHigh = test[i - Convert.ToInt32(TxbxSmallPivotHigh.Text)].Last;
                            if (Math.Abs(test[i - Convert.ToInt32(TxbxSmallPivotHigh.Text)].SmallPivotHigh) > 0.00001 &&
                                Math.Abs(test[i - Convert.ToInt32(TxbxSmallPivotHigh.Text)].SmallPivotHigh - smallHighPivot) > 0.000001)
                                smallHighPivot = test[i - Convert.ToInt32(TxbxSmallPivotHigh.Text)].SmallPivotHigh;
                        }

                        if (pivot.Calculation(test, i - Convert.ToInt32(TxbxSmallPivotHigh.Text), Convert.ToInt32(TxbxNumTicksForInit.Text),
                            Convert.ToInt32(TxbxSmallPivotLow.Text), Convert.ToInt32(TxbxSmallPivotLow.Text), "LOW"))
                        {
                            test[i - Convert.ToInt32(TxbxSmallPivotHigh.Text)].SmallPivotLow = test[i - Convert.ToInt32(TxbxSmallPivotHigh.Text)].Last;
                            if (Math.Abs(test[i - Convert.ToInt32(TxbxSmallPivotHigh.Text)].SmallPivotLow) > 0.00001 &&
                                Math.Abs(test[i - Convert.ToInt32(TxbxSmallPivotHigh.Text)].SmallPivotLow - smallLowPivot) > 0.000001)
                                smallLowPivot = test[i - Convert.ToInt32(TxbxSmallPivotHigh.Text)].SmallPivotLow;
                        }
                    }

                    #endregion

                    #region Pivot Big
                    if (i - Convert.ToInt32(TxbxBigPivotHigh.Text) > 0)
                    {
                        if (pivot.Calculation(test, i - Convert.ToInt32(TxbxBigPivotHigh.Text), Convert.ToInt32(TxbxNumTicksForInit.Text),
                            Convert.ToInt32(TxbxBigPivotHigh.Text), Convert.ToInt32(TxbxBigPivotHigh.Text), "HIGH"))
                        {
                            test[i - Convert.ToInt32(TxbxBigPivotHigh.Text)].BigPivotHigh = test[i - Convert.ToInt32(TxbxBigPivotHigh.Text)].Last;
                            if (Math.Abs(test[i - Convert.ToInt32(TxbxBigPivotHigh.Text)].BigPivotHigh) > 0.000001 &&
                                Math.Abs(test[i - Convert.ToInt32(TxbxBigPivotHigh.Text)].BigPivotHigh - bigHighPivot) > 0.000001)
                                bigHighPivot = test[i - Convert.ToInt32(TxbxBigPivotHigh.Text)].BigPivotHigh;
                        }

                        if (pivot.Calculation(test, i - Convert.ToInt32(TxbxBigPivotHigh.Text), Convert.ToInt32(TxbxNumTicksForInit.Text),
                            Convert.ToInt32(TxbxBigPivotLow.Text), Convert.ToInt32(TxbxBigPivotLow.Text), "LOW"))
                        {

                            test[i - Convert.ToInt32(TxbxBigPivotHigh.Text)].BigPivotLow = test[i - Convert.ToInt32(TxbxBigPivotHigh.Text)].Last;
                            if (Math.Abs(test[i - Convert.ToInt32(TxbxBigPivotHigh.Text)].BigPivotLow) > 0.00001 &&
                                Math.Abs(test[i - Convert.ToInt32(TxbxBigPivotHigh.Text)].BigPivotLow - bigLowPivot) > 0.000001)
                                bigLowPivot = test[i - Convert.ToInt32(TxbxBigPivotHigh.Text)].BigPivotLow;
                        }
                    }

                    #endregion

                    #region MACD Small

                    if (i >= 32)// Convert.ToInt32(TxbxSmallSlowForSignalLine.Text) + Convert.ToInt32(TxbxSmallMacd.Text)-3)
                    {
                        test[i].SmallSignalLineAvgFast = macd.Average(test[i].Last, test[i - 1].SmallSignalLineAvgFast,
                            i, Convert.ToInt32(TxbxSmallFastForSignalLine.Text));
                        test[i].SmallSignalLineAvgSlow = macd.Average(test[i].Last, test[i - 1].SmallSignalLineAvgSlow,
                            i, Convert.ToInt32(TxbxSmallSlowForSignalLine.Text));
                        test[i].SmallSignalLine = Math.Round(test[i].SmallSignalLineAvgFast - test[i].SmallSignalLineAvgSlow, 6);
                        test[i].SmallMacd = Math.Round(macd.AverageMacd(test[i].SmallSignalLine, test[i - 1].SmallMacd,
                            i, Convert.ToInt32(TxbxSmallMacd.Text)), 6);
                        test[i].SmallDiff = macd.MacdDiff(test[i].SmallSignalLine, test[i].SmallMacd);
                        test[i].SmallCountDiff = macd.Count(test[i - 1].SmallDiff, test[i].SmallDiff,
                            test[i - 1].SmallCountDiff);
                    }


                    #endregion

                    #region MACD Big

                    if (i >= 32)// Convert.ToInt32(TxbxBigSlowForSignalLine.Text) + Convert.ToInt32(TxbxBigMacd.Text) - 3)
                    {
                        test[i].BigSignalLineAvgFast = macd.Average(test[i].Last, test[i - 1].BigSignalLineAvgFast,
                            i, Convert.ToInt32(TxbxBigFastForSignalLine.Text));
                        test[i].BigSignalLineAvgSlow = macd.Average(test[i].Last, test[i - 1].BigSignalLineAvgSlow,
                            i, Convert.ToInt32(TxbxBigSlowForSignalLine.Text));
                        test[i].BigSignalLine = Math.Round(test[i].BigSignalLineAvgFast - test[i].BigSignalLineAvgSlow, 6);
                        test[i].BigMacd = Math.Round(macd.AverageMacd(test[i].BigSignalLine, test[i - 1].BigMacd,
                            i, Convert.ToInt32(TxbxBigMacd.Text)), 6);
                        test[i].BigDiff = macd.MacdDiff(test[i].BigSignalLine, test[i].BigMacd);
                        test[i].BigCountDiff = macd.Count(test[i - 1].BigDiff, test[i].BigDiff,
                            test[i - 1].BigCountDiff);
                    }


                    #endregion
                }
            }

        }

        #region Обработка получение текстобксом фокуса и потери его, замена запятой на точку

        private void TxbxLostFocus(object sender, RoutedEventArgs e)
        {
            if (((TextBox)sender).Text == "")
                ((TextBox)sender).Text = 0.ToString();

            char pointChar = ',';
            string str = (1.2).ToString();
            if (str.IndexOf('.') > 0) pointChar = '.';

            if (pointChar == ',')
                ((TextBox)sender).Text = ((TextBox)sender).Text.Replace('.', pointChar);

            if (pointChar == '.')
                ((TextBox)sender).Text = ((TextBox)sender).Text.Replace(',', pointChar);


        }

        private void TxbxGotFocus(object sender, RoutedEventArgs e)
        {
            try
            {
                if (((TextBox)sender).Text != "")
                {
                    if (Convert.ToDouble(((TextBox)sender).Text) == 0)
                    {
                        ((TextBox)sender).Text = "";
                    }
                }
            }
            catch
            {
                ((TextBox)sender).Text = "";
            }
        }

        private void TxbxPreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            if (!Char.IsDigit(e.Text, 0))
                e.Handled = true;

            if ((e.Text.IndexOf('.') == 0 || e.Text.IndexOf(',') == 0) && ((TextBox)sender).Text.IndexOf('.') == -1 && ((TextBox)sender).Text.IndexOf(',') == -1)
                e.Handled = false;

            if (e.Text.IndexOf('-') == 0 && ((TextBox)sender).Text.IndexOf('-') == -1)
                e.Handled = false;
        }

        private void TxbxDitgitPreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            if (!Char.IsDigit(e.Text, 0))
                e.Handled = true;
        }
        #endregion
    }
}
